package com.aoxin.service.impl.activity;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.aoxin.model.activity.SlfRecommendMoneySale;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;

import com.aoxin.mapper.activity.RecommendMoneyMapper;
import com.aoxin.mapper.activity.SlfCashMapper;
import com.aoxin.mapper.activity.SlfRecommendedThresholdMapper;
import com.aoxin.mapper.opm.SlfUserMapper;
import com.aoxin.model.activity.SlfRecommendMoney;
import com.aoxin.model.opm.SlfUser;
import com.aoxin.service.inter.activity.RecommendMoneyService;
import com.aoxin.util.ErrorUtil;
import com.aoxin.util.ThreadLocalUtil;
import com.aoxin.util.enumerate.IsWithdraw;
/**
 * 推荐金额impl
 * @author lop
 * @date 2018年4月28日 上午12:16:54
 */
@Service("recommendMoneyServiceImpl")
public class RecommendMoneyServiceImpl implements RecommendMoneyService {
	@Autowired
	RecommendMoneyMapper recommendMoneyMapper;
	 @Autowired
	 private SlfUserMapper slfUserMapper;
	@Autowired
	SlfCashMapper slfcashMapper;
	private static String IS_UPDATEALL="Y";
	private static Integer FRISTVALUE=0;
	private static String KEY="KEY";
	private static String VALUE="VALUE";
	private static String LIMIT="LIMIT";
	private static String FAMONEY="FAMONEY";
	
	@Autowired
	SlfRecommendedThresholdMapper slfrecommendedthresholdmapper;
	
	@Override
	public List<SlfRecommendMoney> getRecommendMoney(SlfRecommendMoney slfRecommendMoney) {
		return this.recommendMoneyMapper.getRecommendMoney(slfRecommendMoney);
	}

	@Override
	@Transactional
	public void insertRecommendMoney(SlfRecommendMoney slfRecommendMoney) {
		Assert.notNull(slfRecommendMoney.getRefereeId(), String.format(ErrorUtil.PARAMETER_NULL, "RefereeId"));
		this.recommendMoneyMapper.insertSelective(slfRecommendMoney);
	}

	@Override
	@Transactional
	public void insertRecommendMoneySale(SlfRecommendMoneySale slfRecommendMoneySale) {
		Assert.notNull(slfRecommendMoneySale, String.format(ErrorUtil.PARAMETER_NULL, "slfRecommendMoneySale"));
		this.recommendMoneyMapper.insertRecommendMoneySale(slfRecommendMoneySale);
	}

	@Override
	@Transactional
	public List<SlfRecommendMoneySale> queryRecommendMoneySale(SlfRecommendMoneySale slfRecommendMoneySale) {
		return this.recommendMoneyMapper.queryRecommendMoneySale(slfRecommendMoneySale);
	}

	@Override
	@Transactional
	public SlfRecommendMoney updateRecommendMoney(SlfRecommendMoney slfRecommendMoney,Integer type) {
		/**
		 * 判断type类型   --- 1   200<=充值金额<10000   2 10000<= 充值金额
		 *  充值金额大于10000 只修改当前用户金额
		 *  充值金额10000 按原来思路走但是的剔除金额为400的 
		 *   父父级返利不变
		 * 
		 */
		Integer number=0;
		Integer money=0;
		// 更新提现金额数据
		Assert.notNull(slfRecommendMoney, String.format(ErrorUtil.PARAMETER_NULL, "slfRecommendMoney"));
		//查询出上级 --传递过来下级id
		List<SlfRecommendMoney> recommendMoneyList= this.recommendMoneyMapper.getRecommendMoney(slfRecommendMoney);
		SlfRecommendMoney superSlfRecommendMoney=new SlfRecommendMoney();
		//获取设置阈值  -- 无： 使用默认阈值
		List<Map<String,Object>> slfrecommendedthresholdData=slfrecommendedthresholdmapper.getRecommendedThresholdDataNameAndValue();
		if(slfrecommendedthresholdData==null||slfrecommendedthresholdData.size()==0){
			//TODO 设置默认阈值 
			slfrecommendedthresholdData=getDefaultSlfrecommendedThreshoId(slfrecommendedthresholdData);
		}
		// 获取默认 父父级基准值，默认取第一个 为空则设置 为10
		Integer limit = slfrecommendedthresholdData.get(FRISTVALUE).get(LIMIT) == null ? 10
				: Integer.parseInt(slfrecommendedthresholdData.get(FRISTVALUE).get(LIMIT).toString());
		//获取默认推广奖励上限 默认40
		Integer famoney = slfrecommendedthresholdData.get(FRISTVALUE).get(FAMONEY) == null ? 40
				: Integer.parseInt(slfrecommendedthresholdData.get(FRISTVALUE).get(FAMONEY).toString());
		for (SlfRecommendMoney slfRecommendMoneyS : recommendMoneyList) {
			if(type==2){
				money=400;
			}else{
				//新添設置默認基準值
				//this.recommendMoneyMapper.updateRecommendMoney(new BigDecimal(10), slfRecommendMoneyS.getReferralsId(), null);
				// 剔除400 的 推荐用户
				Integer countReferrals=this.recommendMoneyMapper.getReferralsCount(slfRecommendMoneyS.getRefereeId());
				//TODO 未剔除尊享用户
				if(countReferrals>=0){
					//获取阈值人数和金额
					for(int i=0,b=slfrecommendedthresholdData.size();i<b;i++){
						  number=Integer.parseInt(slfrecommendedthresholdData.get(i).get(KEY).toString()); 
						if((countReferrals+1)<number){
							//默认取前一个
							number=	Integer.parseInt(slfrecommendedthresholdData.get(i-1).get(KEY).toString()); 
							money=Integer.parseInt(slfrecommendedthresholdData.get(i-1).get(VALUE).toString()); 
							break;
						}else if((countReferrals+1)==number){
							// 取当前
							money=Integer.parseInt(slfrecommendedthresholdData.get(i).get(VALUE).toString()); 
							break;
						}else{
							number=0;
							money=Integer.parseInt(slfrecommendedthresholdData.get(i).get(VALUE).toString()); 
							continue;
						}
					}
					//更新所有
					this.recommendMoneyMapper.updateRecommendMoney(new BigDecimal(money), slfRecommendMoneyS.getRefereeId(), IS_UPDATEALL );	
				}
			}
			//给当前用户写入数据
			this.recommendMoneyMapper.updateRecommendMoney(new BigDecimal(money), slfRecommendMoneyS.getReferralsId(), null);
			superSlfRecommendMoney.setReferralsId(slfRecommendMoneyS.getRefereeId());
			//获取父父级数据
			List<SlfRecommendMoney> superRecommendMoneyList= this.recommendMoneyMapper.getRecommendMoney(superSlfRecommendMoney);
			//父父级数据由调用方更新  PaymentServiceImpl
			if(superRecommendMoneyList.size()>0){
				superSlfRecommendMoney.setRecommendMoney(new BigDecimal(limit));
				superSlfRecommendMoney.setRefereeId(superRecommendMoneyList.get(0).getRefereeId());
			}
			superSlfRecommendMoney.setReferralsId(null);
			
		}
		return  superSlfRecommendMoney;
	}

	@Override
	@Transactional
	public Integer updateIsWithdraw(Integer cashId,Integer userId,Integer isWithdraw,Integer cashType) {
		/**
		 *  条件，表主键+user_id  改变原因，提现表并未写入子子级数据
		 * 从提现历史中获取子级ID
		 */
		/**
		 *  通过被推荐ID 更新推荐表数据
		 * 
		 * 更新推荐表数据
		 * 更新提现历史数据。
		 * 更新子子级提现状态
		 * 
		 * 提现立方币自动添加 在状态为提现完成的时候
		 * 
		 */
		Map<String,Object>  resultMap= slfcashMapper.getCashDataByUserIdAndCashId(cashId,userId);
		//被推荐人ID
		String[]  strID=resultMap.get("recommend_money_id").toString().split(",");
		List<Integer> referralsIdS=new ArrayList<Integer>();
		for (String  str : strID) {
			referralsIdS.add(Integer.parseInt(str));
		}
		
		for (Integer referralsId : referralsIdS) {
			SlfRecommendMoney slfrecommendmoney=new SlfRecommendMoney();
			slfrecommendmoney.setRefereeId(referralsId);
			//查询出子级与孙子级对应关系
			List<SlfRecommendMoney> recommendMoneyList= this.recommendMoneyMapper.getRecommendMoney(slfrecommendmoney);
			//更新孙子级状态
			for (SlfRecommendMoney slfRecommendMoney2 : recommendMoneyList) {
			 	SlfUser slfUser = new SlfUser();
                slfUser.setUserId(slfRecommendMoney2.getReferralsId());
                slfUser.setIsWinners(isWithdraw);
			  this.slfUserMapper.updateByPrimaryKeySelective(slfUser);
		}
		}
		// 更新提现记录表数据
		this.slfcashMapper.updateSlfCash(cashId,userId, isWithdraw);
		 Integer integer=Integer.parseInt(resultMap.get("cash_money").toString()); 
			//状态1为立方币 直接充值到用户账户
			if(isWithdraw==IsWithdraw.BRINGUPSUCCESS.getId()&&cashType==1){
				  SlfUser user = this.slfUserMapper.selectByPrimaryKey(userId);
					SlfUser userdata=new SlfUser();
					userdata.setUserId(userId);
					userdata.setLfb(user.getLfb()+integer);
				  this.slfUserMapper.updateByPrimaryKeySelective(userdata);
			}
			//更新推荐表数据
		return  this.recommendMoneyMapper.updateIsWithdraw(referralsIdS, isWithdraw);
	}

	@Override
	public List<Integer> effectiveNumber() {
		Integer refereeId=ThreadLocalUtil.getUser().getUserId();
		List<Integer> effectiveNumberAndcumulativeIncome=new ArrayList<Integer>();
		effectiveNumberAndcumulativeIncome.add(this.recommendMoneyMapper.effectiveNumber(refereeId));
		effectiveNumberAndcumulativeIncome.add(this.recommendMoneyMapper.cumulativeIncome(refereeId));
		if (this.recommendMoneyMapper.canWithdrawMoney(refereeId) == null) {
			effectiveNumberAndcumulativeIncome.add(0);
		}else { 
			//TODO 计算子子级数据   待更新子子级提现数据
			effectiveNumberAndcumulativeIncome.add(this.recommendMoneyMapper.canWithdrawMoney(refereeId));			
		}
		return effectiveNumberAndcumulativeIncome;
	}
	
	private List<Map<String,Object>> getDefaultSlfrecommendedThreshoId(List<Map<String,Object>> slfrecommendedthresholdData){
		Map<String,Object> map=new HashMap<String, Object>();
		map.put("KEY", 1);
		map.put("VALUE", 10);
		slfrecommendedthresholdData.add(map);
		map=new HashMap<String, Object>();
		map.put("KEY", 2);
		map.put("VALUE", 13);
		slfrecommendedthresholdData.add(map);
		map=new HashMap<String, Object>();
		map.put("KEY", 5);
		map.put("VALUE", 16);
		slfrecommendedthresholdData.add(map);
		map=new HashMap<String, Object>();
		map.put("KEY", 8);
		map.put("VALUE",20);
		slfrecommendedthresholdData.add(map);
		map=new HashMap<String, Object>();
		map.put("KEY", 15);
		map.put("VALUE", 30);
		slfrecommendedthresholdData.add(map);
		return slfrecommendedthresholdData;
	}
	  
}
